using System;
using Application.Services.PartnersManagement;
using Infrastructure.Data;
using Microsoft.Practices.Unity;

namespace Infrastructure.IoC
{
    public class ServiceFactory
    {
        #region Singleton Pattern Imp

        static ServiceFactory _currentFactory = new ServiceFactory();

        // Current instance of IoCFactory
        public static ServiceFactory CurrentFactory
        {
            get
            {
                return _currentFactory;
            }
        }

        // Prevent "before field init" IL annotation
        static ServiceFactory() { }

        #endregion // Singleton Pattern Imp

        private static IUnityContainer _container;
        private static IMainModuleUnitOfWork _unitOfWork;
        
        #region Constructor

        ServiceFactory()
        {
            //Create root container
            _container = new UnityContainer();

            //Create Entity framework Context
            _unitOfWork = new MainModuleUnitOfWork();

            ConfigureRootContainer(_container);
        }

        #endregion

        #region Properties

        public IUnityContainer Container
        {
            get { return _container; }
        }

        #endregion

        #region Private Methods

        static void ConfigureRootContainer(IUnityContainer container)
        {

            //Register Services mappings
            //container.RegisterType<IMainModuleService, FakeMainModuleService>();
            container.RegisterType<IPartnersManagementService, PartnersManagementService>(new InjectionConstructor(_unitOfWork));

        }

        #endregion // Private Methods

        #region Public Methods

        public static TService Resolve<TService>()
        {
            return _container.Resolve<TService>();
        }

        public static void RegisterType(Type type)
        {
            if (_container != null)
                _container.RegisterType(type, new TransientLifetimeManager());
        }

        public static object Resolve(Type type)
        {
            return _container.Resolve(type, null);
        }

        #endregion // Public Methods
    }
}